package com.tools.cleanmaster.ui.card;

import android.app.Activity;
import android.view.View;

import com.google.android.gms.ads.AdView;
import com.hm.ads.sdk.HmAdsSDK;
import com.hm.adsbuisiness.bean.HmAdUnionPlace;
import com.tools.ad.EntranceType;
import com.tools.ad.ui.crad.view.AmBannerCardView;
import com.tools.cleanmaster.ui.card.factory.CardListAdapter;
import com.tools.cleanmaster.ui.card.viewholder.ACardViewHolder;
import com.tools.cleanmaster.ui.card.viewholder.LoadingAdCardViewHolder;

/**
 * 广告卡片
 */
public class LoadingAdCardItem extends BaseAdCard {


    public LoadingAdCardItem(EntranceType entranceType, int pos) {
        super(entranceType, pos);
    }

    @Override
    public boolean needShow(EntranceType eType) {
        HmAdUnionPlace adUnionPlace = HmAdsSDK.getInstance().getUnionAd(mEntranceType.getPid());
        if (adUnionPlace == null) {
            return false;
        }

        return true;
    }

    public String getTitle() {
        return "";
    }

    @Override
    public String getCardName() {
        return CardType.LOADING_AD.key;
    }

    @Override
    public CardViewType getCardViewType() {
        return CardViewType.LOADING_AD;
    }

    @Override
    public void bindCardView(final Activity activity, ACardViewHolder viewHolder, CardListAdapter cardAdapter, final int position) {
        super.bindCardView(activity, viewHolder, cardAdapter, position);

        LoadingAdCardViewHolder advertViewHolder = (LoadingAdCardViewHolder) viewHolder;

        //由于刷新的时候，并不会在AdvertView，所以这里再重复了一遍LoadingAdCardViewHolder的代码
        if (advertViewHolder.mAdvertView == null) {
            View cardView = advertViewHolder.mEntrance.getAdScene().getAdView();
            if (cardView != null) {
                //admob banner view
                if (cardView instanceof AdView) {
                    AmBannerCardView amBannerCardView = new AmBannerCardView(activity.getApplicationContext());
                    amBannerCardView.addAdView(cardView);
                    advertViewHolder.mAdvertView = amBannerCardView;
                } else {
                    advertViewHolder.mAdvertView = cardView;
                }
            }
        }

        if (advertViewHolder.mAdvertView != null && !haveAddAdvertView(advertViewHolder)) {
            advertViewHolder.mAdLayout.removeAllViews();
            advertViewHolder.mAdLayout.addView(advertViewHolder.mAdvertView);
        }
    }

    /**
     * 预防，多次移除，添加。
     *
     * @param advertViewHolder
     * @return
     */
    private boolean haveAddAdvertView(LoadingAdCardViewHolder advertViewHolder) {
        return advertViewHolder.mAdLayout.indexOfChild(advertViewHolder.mAdvertView) != -1;
    }

    @Override
    public void onActivityDestroy() {
        mEntranceType.getAdScene().release();
    }


}
